import { defineStore } from "pinia";
import products from './products'


// 产品状态
export const productsStore = defineStore("products", {
  state: () => ({
    productsList: [],
  }),
  getters: {
    brands: (state) => {
      const brands = state.productsList.map((item) => item.brand);
      return getFilterArray(brands);
    },
    colors: (state) => {
      const colors = state.productsList.map((item) => item.color);
      return getFilterArray(colors);
    },
  },
  actions: {

    // 请求商品列表
    getProductList() {
      // 真实环境通过 ajax 获取，这里用异步模拟
      setTimeout(() => {
        this.setProductList(products)
      }, 500);
    },

    // 设置产品列表
    setProductList(data) {
      // push 解构数组的时候会重复添加
      //   this.productsList.push(...data)
      return this.productsList = data;
    },

  },
});



// 购物车状态
export const cartStore = defineStore("cart", {
  state: () => ({
    cartList: [],
  }),
  actions: {
    // 添加到购物车
    addCart(id) {
      // 先判断购物车是否已有，如果有，数量+1
      const isAdded = this.cartList.find((item) => item.id === id);
      if (isAdded) {
        isAdded.count++;
      } else {
        this.cartList.push({
          id: id,
          count: 1,
        });
      }
    },
    // 修改商品数量
    editCartCount(payload) {
      const product = this.cartList.find((item) => item.id === payload.id);
      product.count += payload.count;
    },
    // 删除商品
    deleteCart(id) {
      const index = this.cartList.findIndex((item) => item.id === id);
      this.cartList.splice(index, 1);
    },
    // 清空购物车
    emptyCart() {
      this.cartList = [];
    },
    // 购买
    async buy() {
      // 真实环境应通过 ajax 提交购买请求后再清空购物列表
      await new Promise(resolve => {
        setTimeout(() => {
          resolve();
        }, 500)
      });

      this.emptyCart()

    }
  },
});


/* 公共方法 */

/* 数组排重 */
function getFilterArray(array) {
  let res = [];
  let json = {};
  for (let i = 0; i < array.length; i++) {
    let _self = array[i];
    if (!json[_self]) {
      res.push(_self);
      json[_self] = 1;
    }
  }
  return res;
}
